import {Component, ViewEncapsulation, Input, Output, EventEmitter, ViewChild} from '@angular/core';
import {Utility} from '../../../../../services/app.utility';
import {IdeaService} from '../../../../../services/app.idea';
import {UserService} from '../../../../../services/app.user';
import {AuthenticationHelper} from '../../../../../app.authentication';
import {BaThemeSpinner}  from '../../../../../theme/services';
import {Constants} from '../../../../../common/app.constants';
import {Modal} from 'ngx-modal';
declare let toastr:any;
declare let $:any;
declare let Treant:any;

@Component({
    selector: 'viewCardIdeaDetail',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./viewCardIdeaDetail.scss'],
    templateUrl: './viewCardIdeaDetail.html'

})

export class viewCardIdeaDetail {
    @Input()
    viewDetailIdea:any;
    @Output()
    notifyParent:EventEmitter<any> = new EventEmitter();
    @Output()
    notifyParenttoProfile:EventEmitter<any> = new EventEmitter();
    @ViewChild('citationTreedialog')
    public citationTreeModaldialog:Modal;

    @Input()
    constants:Constants;
    public selectedDeleteComment:any;
    public commentListOfIdea:any;
    public versioning:boolean;
    public commentWait:boolean = true;
    public start:any;
    public end:any;
    public check:any;
    public clickPointer:any;
    public deleteModal:boolean;
    public modalPostComment:boolean;
    public cardcommentinput:any;
    public viewMoreComment:boolean;

    constructor(public utility:Utility, private spinner:BaThemeSpinner, private userService:UserService, private ideaService:IdeaService, private authentication:AuthenticationHelper) {
        this.constants = new Constants();
        this.viewDetailIdea = {};
        this.commentListOfIdea = {
            'ideaId': this.viewDetailIdea._id,
            'skipItem': 0,
            'itemsperPage': 6,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };

        this.versioning = false;
        this.clickPointer = this.utility.clickFromProfile;

        // API call for get user info
        /*this.userService.getuserInfo().subscribe(
            data => this.userInfoSuccess(data),
            error => this.userInfoFail(error)
        );*/

        this.start = 0;
        this.check = 0;

        // Function call for start timeline count
        this.startCount();
    };


    //  Convert Date to MM/DD/YY
    public formateDate(dates):any {
        return this.utility.getFormattedDateForTree(dates);
    }

    public formateDatewithTime(dates):any {
        return this.utility.getAgoDate(this.utility.getFormattedDate(dates));
    }


    // Notify Parent for Abuse
    public setAbuse(idea) {
        this.notifyParent.emit(idea);
    }

    // View Profile
    public viewProfile(idea) {
        if (!this.utility.clickFromProfile) {
            this.notifyParenttoProfile.emit(idea);
        }
    }

    // Adding Likes count and API call
    public likesCount(idea) {
        this.spinner.showProgress();
        let ideasData = {
            'ideaId': idea._id,
            'voteType': 'like'
        };
        this.ideaService.ideaLikes(ideasData).subscribe(
            data => this.likesuccess(data, idea),
            error => this.likefail(error)
        );
    }

    // Function call if like successfully
    public likesuccess(result, idea) {
        this.spinner.hideProgress();

        if (result.voteType.length > 0 && result.voteType === 'like') {
            idea.likes = result.idea.likes;
            idea.dislikes = result.idea.dislikes;
            idea.points = result.idea.points;

            idea.isliked = true;
            idea.isdisliked = false;

            toastr.success(this.constants.LIKEIDEA);
        } else {
            idea.likes = result.idea.likes;
            idea.dislikes = result.idea.dislikes;
            idea.points = result.idea.points;

            idea.isliked = false;
            idea.isdisliked = false;
            toastr.success(this.constants.REMOVELIKEIDEA);
        }
    }

    // Function call if like failed
    public likefail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }


    // Adding dislike count and call API
    public dislikesCount(idea) {
        this.spinner.showProgress();
        let ideasData = {
            'ideaId': idea._id,
            'voteType': 'dislike'
        };
        this.ideaService.ideaLikes(ideasData).subscribe(
            data => this.dislikesuccess(data, idea),
            error => this.dislikefail(error)
        );
    }

    // Function call if dislike successfully
    public dislikesuccess(result, idea) {

        this.spinner.hideProgress();

        if (result.voteType.length > 0 && result.voteType === 'dislike') {
            idea.likes = result.idea.likes;
            idea.dislikes = result.idea.dislikes;
            idea.points = result.idea.points;

            idea.isliked = false;
            idea.isdisliked = true;

            toastr.success(this.constants.DISLIKE);
        } else {
            idea.likes = result.idea.likes;
            idea.dislikes = result.idea.dislikes;
            idea.points = result.idea.points;

            idea.isdisliked = false;
            idea.isliked = false;

            toastr.success(this.constants.REMOVEDISLIKE);
        }
    }

    // Function call if dislike failed
    public dislikefail(error) {
        toastr.error(error.error_message);
        this.spinner.hideProgress();
    }


    // Adding Favourite Count and color red
    public favouriteCount(idea) {
        this.spinner.showProgress();
        let favouriteType = 'addFavourite';
        if (idea.isfavorite === true) {
            favouriteType = 'removeFavourite';
            idea.isfavorite = false;
        } else {
            favouriteType = 'addFavourite';
            idea.isfavorite = true;
        }
        let favouriteData = {
            'ideaId': idea._id,
            'favouriteType': favouriteType
        };
        this.ideaService.faouriteLikes(favouriteData).subscribe(
            data => this.favouritesuccess(data, idea),
            error => this.favouritefail(error)
        );
    }

    // Function call if favourite successfully
    public favouritesuccess(result, idea) {

        if (idea.isfavorite === true) {
            toastr.success(this.constants.FAVOURITEIDEA);
        } else {
            toastr.error(this.constants.REMOVEFAVOURITEIDEA);
        }

        this.spinner.hideProgress();
        result.isfavorite = !result.isfavorite;
    }

    // Function call if favourite failed
    public favouritefail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);

    }


    // delete comment Modal PopUp
    public deleteModalOpen(cardcommentsInfo) {
        this.selectedDeleteComment = cardcommentsInfo;
        this.deleteModal = true;
    }

    // Delete Call API on OK
    public deleteComment(viewDetailIdea) {
        this.spinner.showProgress();
        this.deleteModal = false;
        let cardData = {
            'ideaId': viewDetailIdea._id,
            'commentId': this.selectedDeleteComment._id
        };

        this.ideaService.deleteComments(cardData).subscribe(
            data => this.deleteCommentsSuccess(data, viewDetailIdea),
            error => this.deleteCommentfail(error)
        );
    }

    // Fuction for delete comment successfully and get new data from server
    public deleteCommentsSuccess(data, viewDetailIdea) {
        --viewDetailIdea.data.commentCount;
        --viewDetailIdea.commentcount;

        let input = {
            'ideaId': viewDetailIdea._id,
            'skipItem': 0,
            'itemsperPage': 6,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.ideaService.getcardComment(input).subscribe(
            data => this.getCommentsUpdate(data, viewDetailIdea),
            error => this.getcommentfail(error)
        );
    }

    // Fuction for delete comment failed
    public deleteCommentfail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);

    }


    // more comment API call
    public getMoreComment(viewDetailIdea) {
        this.commentListOfIdea.ideaId = viewDetailIdea._id;
        this.commentListOfIdea.skipItem += this.commentListOfIdea.itemsperPage;
        this.spinner.showProgress();
        this.ideaService.getcardComment(this.commentListOfIdea).subscribe(
            data => this.getCommentsUpdate(data, viewDetailIdea),
            error => this.getcommentfail(error)
        );

    }

    // Function call more comment update successfully
    public getCommentsUpdate(data, viewDetailIdea) {
        this.spinner.hideProgress();
        viewDetailIdea.data.commentList = data.commentList;
        if ((data.commentcount - this.commentListOfIdea.skipItem) > this.commentListOfIdea.itemsperPage) {
            this.viewMoreComment = false;
        } else {
            this.viewMoreComment = true;
        }
    }

    // Fuction for delete comment successfully
    public  getcommentsuccess(data, viewDetailIdea) {
        viewDetailIdea.data.commentList = data.commentList;
        viewDetailIdea.data.commentCount = data.commentCount;
        toastr.success(this.constants.DELETED);
        this.spinner.hideProgress();

    }

    // Fuction for more comment failed
    public getcommentfail(error) {
        this.spinner.hideProgress();
    }


    // adding comment function call
    public addcardComment(comment, viewDetailIdea) {
        comment = comment.trim();
        if (comment.length > 0) {
            if (this.commentWait === true) {
                this.modalPostComment = true;
                this.commentWait = false;
                this.spinner.showProgress();
                let cardData = {
                    'ideaId': this.viewDetailIdea._id,
                    'comment': comment
                };
                this.ideaService.addcardComment(cardData).subscribe(
                    data => this.addcommentsuccess(data, comment, viewDetailIdea),
                    error => this.addcommentfail(error)
                );
            }
        }
    }

    // Function call if comment success and increase count
    public addcommentsuccess(data, comment, viewDetailIdea) {
        toastr.success(this.constants.COMMENTDELETE);
        this.spinner.hideProgress();
        this.commentWait = true;
        this.modalPostComment = false;
        this.cardcommentinput = '';
        let newComment = {
            'comment': comment,
            'createdAt': this.utility.getDatewithoutTimstamp(new Date()),
            'name': this.authentication.getUser().firstName + ' ' + this.authentication.getUser().lastName,
            'isOwner': true,
            '_id': data
        };
        viewDetailIdea.data.commentList.unshift(newComment);
        ++viewDetailIdea.data.commentCount;
        ++viewDetailIdea.commentcount;

        if (viewDetailIdea.commentcount > 6) {
            viewDetailIdea.data.commentList.pop();
        }


        let input = {
            'ideaId': viewDetailIdea._id,
            'skipItem': 0,
            'itemsperPage': 6,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.ideaService.getcardComment(input).subscribe(
            data => this.getCommentsUpdate(data, viewDetailIdea),
            error => this.getcommentfail(error)
        );
    }

    // Function call if comment API return error
    public addcommentfail(data) {
        toastr.error(data.error_message);
        this.commentWait = true;
        this.modalPostComment = false;
    }

    // Function for split and join color to content
    public switchTags(content) {
        return content.split('keywordColor').join('keywordColors');
    }

    // Function call if user info API success and lock version
    public userInfoSuccess(data) {
        console.log("view");
        if (data.version === 'Version_1') {
            this.versioning = false;
        } else if (data.version === 'Version_2') {
            this.versioning = false;
        } else if (data.version === 'Version_4') {
            this.versioning = false;
        } else if (data.version === 'Version_6') {
            this.versioning = false;
        } else {
            this.versioning = true;
        }
    }

    // Function call if user info API failed
    public  userInfoFail(err) {
    }


    // Function for get citation array tree API call
    private getBigTreeData(data):void {
        let inputData = {content: data};
        this.spinner.showProgress();
        this.ideaService.getCitationTreeData(inputData).subscribe(
            data => this.generateTreeModal(data),
            error => {
            });
    }

    // function for get citation tree data API call
    public getTreeDataModal(data):void {
        let inputData = {content: [data]};
        this.spinner.showProgress();
        this.ideaService.getCitationTreeData(inputData).subscribe(
            data => this.generateTreeModal(data),
            error => {
            });
    }

    // function for generate citation tree
    public generateTreeModal(data) {
        this.citationTreeModaldialog.open();
        setTimeout(() => {
            let chartConfig = {
                chart: {
                    container: '#tree-simpl',
                    scrollbar: 'fancy',
                    siblingSeparation: 20,
                    subTeeSeparation: 60,
                    connectors: {
                        type: 'step'
                    },
                    node: {
                        HTMLclass: 'nodeExample1'
                    }
                },
                nodeStructure: data

            };
            let chart = new Treant(chartConfig);
        }, 1000);
        this.spinner.hideProgress();
    }

    // User log for keystroke event
    public onKeyPressViewCard(event) {
        let input = {
            'target': 'Input user comment...',
            'action': 'keystroke'
        };
        // API call for send user log data
        this.userService.setUserLogs(input).subscribe();
    }

    // To call every 1 sec for count how much time we spent on this page
    public  timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();
    }
}
